import { createRouter, createWebHashHistory } from 'vue-router'
import { constantRouter } from './routes'
import { TokenStorage } from '@/utils/localStorange.ts'
import { RouterRedirectStorage } from '@/utils/sessionStorange.ts'
const router = createRouter({
    history: createWebHashHistory(),
    routes: constantRouter,
    // 滚动行为
    scrollBehavior: () => ({ left: 0, top: 0 }),
})
// 暂时隐藏重定向到登录
router.beforeEach((to, from, next) => {
    console.log(TokenStorage.get())
    const isLoggedIn = TokenStorage.get()
    const isRedirecting = RouterRedirectStorage.get() // 检查是否正在重定向

    if (isLoggedIn) {
        if (to.path === '/login') {
            next({ path: '/' })
        } else {
            if (from.query._redirect && !isRedirecting) {
                RouterRedirectStorage.set('true') // 设置重定向标记
                // eslint-disable-next-line
                // @ts-expect-error
                next({ path: from.query._redirect })
            } else {
                RouterRedirectStorage.remove() // 清除重定向标记
                next()
            }
        }
    } else {
        if (to.path !== '/login') {
            next(`/login?_redirect=${to.path}`)
        } else {
            next()
        }
    }
})

export default router
